package com.ksd.web.controller.service;

import com.alibaba.fastjson2.JSONObject;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.ksd.common.core.domain.AjaxResult;
import com.ksd.common.utils.StringUtils;
import com.ksd.quartz.http.DRMHttpClient;
import com.ksd.quartz.util.TaskConstans;
import com.ksd.system.domain.SysBoard;
import com.ksd.system.domain.SysChannelTemplate;
import com.ksd.system.service.ISysBoardService;
import com.ksd.system.service.ISysChannelTemplateService;
import com.ksd.system.service.ISysOperLogService;
import com.ksd.web.controller.m3beans.*;
import org.aspectj.weaver.loadtime.Aj;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;


@Service
public class SearchChannelService {
    public final Logger logger = LoggerFactory.getLogger(SearchChannelService.class);
    @Autowired
    private ISysOperLogService sysOperLogService;
    @Autowired
    private SendChannelService sendChannelService;
    @Autowired
    private ISysChannelTemplateService sysChannelTemplateService;

    /**
     * 开始进行搜索
     * @param sysBoard
     * @param startChannelScanData
     * @return
     */
    public int startChannelScan(SysBoard sysBoard, StartChannelScanData startChannelScanData) {
        String url = sysBoard.getUrl();
        StartChannelParameter startChannelParameter = new StartChannelParameter();
        startChannelParameter.setScanType(1);
        TuningParameter tuningParameter = new TuningParameter();
        tuningParameter.setFrequency(startChannelScanData.getFrequency());
        tuningParameter.setSymbolRate(startChannelScanData.getSymbolRate());
        tuningParameter.setPolarization(startChannelScanData.getPolarization());
        List<TuningParameter> list = new ArrayList<>();
        list.add(tuningParameter);
        startChannelParameter.setTuningParameters(list);
        String response = sendChannelService.startChannelScan(startChannelParameter, url);
        sysOperLogService.insertOperlogApiSuccess("频道搜索开始接口.请求地址: " + url + ",响应数据:" + response);
        if (StringUtils.isEmpty(response)) {
            sysOperLogService.insertOperlogApiError("频道搜索开始.请求地址: " + url + ",接口响应超时,请检查网络连接或联系管理员稍后重试");
            return -1;
        }
        ObjectMapper mapperPage = new ObjectMapper();
        StartChannelScanResponse startChannelScanResponse = null;
        try {
            ObjectMapper objectMapper = new ObjectMapper();
            // 将 JSON 字符串解析为 JsonNode 对象
            JsonNode rootNode = objectMapper.readTree(response);
            // 获取 status 节点的值
            int statusInt = rootNode.get("status").asInt();
            if (statusInt != 0) {
                sysOperLogService.insertOperlogApiError("频道搜索开始接口.请求地址: " + url + ",响应状态失败，请联系管理员检查接口服务或稍后重试");
                return -1;
            } else if (statusInt == 0) {
                return 0;
            }
        } catch (JsonProcessingException e) {
            throw new RuntimeException(e);
        }
        return -1;
    }

    /**
     * 停止搜索
     * @param sysBoard
     * @return
     */
    public int stopChannelScanNoGetInfo(SysBoard sysBoard) {
        String url = sysBoard.getUrl();
        String response = sendChannelService.stopChannelScan(url);
        sysOperLogService.insertOperlogApiSuccess("频道搜索结束接口.请求地址: " + url + ",响应数据:" + response);
        if (StringUtils.isEmpty(response)) {
            sysOperLogService.insertOperlogApiError("频道搜索结束接口.请求地址: " + url + ",响应超时,请检查网络连接或联系管理员稍后重试");
            return -1;
        }
        ObjectMapper mapperPage = new ObjectMapper();
        StopChannelScanResponse stopChannelScanResponse = null;
        try {
            ObjectMapper objectMapper = new ObjectMapper();
            // 将 JSON 字符串解析为 JsonNode 对象
            JsonNode rootNode = objectMapper.readTree(response);
            // 获取 status 节点的值
            int statusInt = rootNode.get("status").asInt();
            logger.info("搜索结束接口响应状态:" + statusInt);
            if (statusInt != 0) {
                sysOperLogService.insertOperlogApiError("频道搜索结束接口.请求地址: " + url + ",响应状态失败，请联系管理员检查接口服务或稍后重试");
                return -1;
            } else if (statusInt == 0) {
//                stopChannelScanResponse = mapperPage.readValue(response, StopChannelScanResponse.class);
//                logger.info("搜索结束接口响应数据:" + stopChannelScanResponse.toString());
//                asyncService.sendChannelListManageDataAsync(sysBoard.getId()); //在默认分发频道内不进行异步查询
//                AjaxResult channelListManage = sendChannelService.getChannelListManage(sysBoard.getId());
//                logger.info("获取频道信息接口结果:"+channelListManage.toString());
//                if (channelListManage != null && channelListManage.isSuccess()) {
//                    return 0;
//                }else{
//                    return -1;
//                }
                return 0;
            }
        } catch (JsonProcessingException e) {
            throw new RuntimeException(e);
        }
        return -1;
    }


    /**
     * 停止搜索
     * @param sysBoard
     * @return
     */
    public int stopChannelScan(SysBoard sysBoard) {
        String url = sysBoard.getUrl();
        String response = sendChannelService.stopChannelScan(url);
        sysOperLogService.insertOperlogApiSuccess("频道搜索结束接口.请求地址: " + url + ",响应数据:" + response);
        if (StringUtils.isEmpty(response)) {
            sysOperLogService.insertOperlogApiError("频道搜索结束接口.请求地址: " + url + ",响应超时,请检查网络连接或联系管理员稍后重试");
            return -1;
        }
        ObjectMapper mapperPage = new ObjectMapper();
        StopChannelScanResponse stopChannelScanResponse = null;
        try {
            ObjectMapper objectMapper = new ObjectMapper();
            // 将 JSON 字符串解析为 JsonNode 对象
            JsonNode rootNode = objectMapper.readTree(response);
            // 获取 status 节点的值
            int statusInt = rootNode.get("status").asInt();
            logger.info("搜索结束接口响应状态:" + statusInt);
            if (statusInt != 0) {
                sysOperLogService.insertOperlogApiError("频道搜索结束接口.请求地址: " + url + ",响应状态失败，请联系管理员检查接口服务或稍后重试");
                return -1;
            } else if (statusInt == 0) {
                stopChannelScanResponse = mapperPage.readValue(response, StopChannelScanResponse.class);
                logger.info("搜索结束接口响应数据:" + stopChannelScanResponse.toString());
//                asyncService.sendChannelListManageDataAsync(sysBoard.getId()); //在默认分发频道内不进行异步查询
                AjaxResult channelListManage = sendChannelService.getChannelListManage(sysBoard.getId());
                logger.info("获取频道信息接口结果:"+channelListManage.toString());
                if (channelListManage != null && channelListManage.isSuccess()) {
                    return 0;
                }else{
                    return -1;
                }
            }
        } catch (JsonProcessingException e) {
            throw new RuntimeException(e);
        }
        return -1;
    }

    /**
     * 频道清除
     * @param sysBoard
     * @return
     */
    public int resetProgramDbsData(SysBoard sysBoard) {
        String url = sysBoard.getUrl();
        String response = sendChannelService.resetProgramService(url);
        sysOperLogService.insertOperlogApiSuccess("频道清除接口.请求地址: "+url+",响应数据:"+response);
        if (StringUtils.isEmpty(response)){
            sysOperLogService.insertOperlogApiError("频道清除接口.请求地址: "+url+",响应超时,请检查网络连接或联系管理员稍后重试");
            return -1;
        }
        ObjectMapper mapperPage = new ObjectMapper();
        StopChannelScanResponse stopChannelScanResponse = null;
        try {
            ObjectMapper objectMapper = new ObjectMapper();
            // 将 JSON 字符串解析为 JsonNode 对象
            JsonNode rootNode = objectMapper.readTree(response);
            // 获取 status 节点的值
            int statusInt = rootNode.get("status").asInt();
            if (statusInt != 0) {
                sysOperLogService.insertOperlogApiError("频道清除接口.请求地址: "+url+",响应状态失败，请联系管理员检查接口服务或稍后重试");
                return -1;
            } else if (statusInt == 0) {
                stopChannelScanResponse = mapperPage.readValue(response, StopChannelScanResponse.class);
                //清除完成之后,需要将对应的频道删除
                //清空已配置的频道
                SysChannelTemplate sysChannelTemplate = new SysChannelTemplate();
                sysChannelTemplate.setBoardId(Long.valueOf(sysBoard.getId()));
                sysChannelTemplate.setStatus(TaskConstans.status_selected);
                List<SysChannelTemplate> sysChannelTemplates = sysChannelTemplateService.selectSysChannelTemplateList(sysChannelTemplate);
                for (SysChannelTemplate channelTemplate : sysChannelTemplates) {
                    channelTemplate.setStatus(TaskConstans.status_init);
                    sysChannelTemplateService.updateSysChannelTemplate(channelTemplate);
                }
                return 0;
            }
        } catch (JsonProcessingException e) {
            throw new RuntimeException(e);
        }
        return -1;
    }

    /**
     * 进行频道循环搜索
     * @param sysBoard
     * @param m3Bean
     * @return
     */
    public int repeatedSearchM3GetService(SysBoard sysBoard){
        String url = sysBoard.getUrl();
        M3Request m3RequestInfo = M3Request.getM3RequestInfo(TaskConstans.getServiceInfo);
        String jsonString = JSONObject.toJSONString(m3RequestInfo);
        logger.info("[system-channelSearch] The repeatedSearchM3GetService M3 task get url :" + url);
        logger.info("[system-channelSearch] The repeatedSearchM3GetService M3 task get request :" + jsonString);

        String response = DRMHttpClient.udrmHttpDoGet(url, jsonString);
        sysOperLogService.insertOperlogApiSuccess("频道搜索接口.请求地址: "+url+",响应数据:"+response);
        if (StringUtils.isEmpty(response)){
            sysOperLogService.insertOperlogApiError("频道搜索接口.请求地址: "+url+",响应超时,请检查网络连接或连接管理员稍后重试");
            return -1;
        }
        ObjectMapper objectMapper = new ObjectMapper();
        JsonNode jsonNode = null;
        try {
            jsonNode = objectMapper.readTree(response);
        } catch (JsonProcessingException e) {
            logger.error(e.getMessage());
            throw new RuntimeException(e);
        }
        int status = jsonNode.get("status").asInt();
        if (status == 2) {
            sysOperLogService.insertOperlogApiError("搜索频道接口.请求地址: "+url+",响应状态失败，请联系管理员检查接口服务或稍后重试");
            return status;
        }else if(status == 0){
            sysOperLogService.insertOperlogApiSuccess("搜索频道接口.请求地址: "+url+",搜索完成");
            //如果状态为0,停止查询,执行stop接口
            return status;
        }else if(status == 1){
            //如果状态为1,持续查询
            return status;
        }else{
            return status;
        }
    }

}
